'''
难度 简单
标签 字符串
题目链接 https://leetcode.cn/problems/fan-zhuan-dan-ci-shun-xu-lcof/description/
'''

from typing import List


class Solution:
    # 遍历重组
    def reverseMessage1(self, message: str) -> str:
        l = message.split(' ')
        s = ''

        for i in range(len(l) - 1, -1, -1):
            if l[i] == '':
                continue

            s += ' ' + l[i]
        
        return s[1:]
    
    # 双指针
    def reverseMessage(self, message: str) -> str:
        message = message.strip()
        
        # 因为要倒序输出 所以要从后往前遍历
        i = j = len(message) - 1

        result = []
        while i >= 0:
            # 找到首个空格
            while i >= 0 and message[i] != ' ':
                i -= 1
            # 添加单词
            result.append(message[i + 1 : j + 1])

            # 跳过单词之间的连续空格
            while i >= 0 and message[i] == ' ':
                i -= 1
            
            # 遇见下一个单词的末尾
            j = i
        
        return ' ' . join(result)



    

if __name__ == '__main__':
    s = Solution()
    参数 = [
        ["the sky is blue"],
        ["  hello world!  "],
        ["a good   example"],
    ]
    预期 = [
        "blue is sky the",
        "world! hello",
        "example good a",
    ]
    for k,v in enumerate(参数):
        r = s.reverseMessage(v[0])
        if r != 预期[k]:
            print("第{}个case不通过 期望={} 结果={}\n".format(
                k+1,
                预期[k],
                r
            ))